<template>
  <view class="whitelist-page">
	  <view style="padding:15rpx 25rpx; background: #f5f7fa;">
	  	<u-subsection  :list="list" fontSize="26" :current="current" @change="sectionChange"></u-subsection>
	  </view>
    <!-- 表单区域 -->
    <view class="form-container">
      <view class="form-card">
        <!-- 姓名 -->
        <view class="form-item">
          <text class="item-label"> 姓名</text>
          <view class="item-input">
            <input 
              v-model="form.real_name" 
              placeholder="请输入姓名"
              @input="validateField('real_name')"
            />
          </view>
          <text class="error-message" v-if="errors.real_name">{{ errors.real_name }}</text>
        </view>

        <!-- 证件号码 -->
        <view class="form-item">
          <text class="item-label">证件号码</text>
          <view class="item-input">
            <input 
              v-model="form.idcard" 
              placeholder="请输入证件号码"
              @input="onIdNumberInput"
            />
          </view>
          <text class="tips">请输入18位身份证号码</text>
          <text class="error-message" v-if="errors.idcard">{{ errors.idcard }}</text>
        </view>

        <!-- 从身份证提取的出生日期 -->
        <view class="form-item">
          <text class="item-label">出生日期</text>
          <view class="item-input" style="width: 92%;">
            <text class="readonly-value">{{ birthDate || '请输入有效身份证号码' }}</text>
          </view>
        </view>

        <!-- 身份证有效期开始日期 -->
        <view class="form-item">
          <text class="item-label">有效期开始日期</text>
          <view class="item-input">
            <picker 
              mode="date" 
              :value="form.start_date" 
              start="1900-01-01" 
              end="2100-12-31"
              @change="onStartDateChange"
            >
              <view class="picker">
                {{ form.start_date || '请选择日期' }}
              </view>
            </picker>
          </view>
          <text class="error-message" v-if="errors.start_date">{{ errors.start_date }}</text>
        </view>

        <!-- 身份证有效期结束日期 -->
        <view class="form-item">
          <text class="item-label">有效期结束日期</text>
          <view class="item-input">
            <picker 
              mode="date" 
              :value="form.end_date" 
              :start="form.end_date || '1900-01-01'" 
              end="2100-12-31"
              @change="onExpireDateChange"
            >
              <view class="picker">
                {{ form.end_date || '请选择日期' }}
              </view>
            </picker>
          </view>
         
        </view>

        <!-- 身份证正面 -->
        <view class="form-item">
          <text class="item-label">身份证正面</text>
          <view class="upload-container">
            <view 
              class="upload-box" 
			  :style="{ backgroundImage: `url(${form.idcard_image})` }"
              @click="chooseImage('idcard_image')"
            >
             
              <view v-if="!form.idcard_image" class="upload-placeholder">
				<image style="width: 100%;height: 100%;position: absolute;top: 0;left: 0;" src="/static/add_idcard.png"></image>
                <text class="upload-icon">+</text>
                <text class="upload-text">点击上传</text>
              </view>
            </view>
            <text class="upload-tips">请上传清晰的身份证正面照片</text>
          </view>
          <text class="error-message" v-if="errors.idcard_image">{{ errors.idcard_image }}</text>
        </view>

        <!-- 身份证反面 -->
        <view class="form-item">
          <text class="item-label">身份证反面</text>
          <view class="upload-container">
            <view 
              class="upload-box" 
			  :style="{ backgroundImage: `url(${form.idcard_image_b})` }"
              @click="chooseImage('idcard_image_b')"
            >
              <view v-if="!form.idcard_image_b" class="upload-placeholder">
				  <image style="width: 100%;height: 100%;position: absolute;top: 0;left: 0;" src="/static/add_idcardb.png"></image>
                <text class="upload-icon">+</text>
                <text class="upload-text">点击上传</text>
              </view>
            </view>
            <text class="upload-tips">请上传清晰的身份证反面照片</text>
          </view>
          <text class="error-message" v-if="errors.idcard_image_b">{{ errors.idcard_image_b }}</text>
        </view>

        <!-- 备注 -->
        <view class="form-item">
          <text style="display: block;
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 16rpx;">备注</text>
          <view class="item-input">
            <textarea 
              v-model="form.remark" 
              placeholder="请输入备注信息（选填）"
              maxlength="200"
            />
            <text class="counter">{{ form.remark.length }}/200</text>
          </view>
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="btn-container">
        <button 
          class="submit-btn" 
          @click="submitForm"
        >
          确认提交
        </button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      form: {
        real_name: '',
        idcard: '',
        start_date: '',
        end_date: '',
        idcard_image: '',
        idcard_image_b: '',
        remark: ''
      },
      errors: {
        real_name: '',
		idcard: '',
		start_date: '',
		end_date: '',
		idcard_image: '',
		idcard_image_b: '',
		remark: ''
      },
      birthDate: '', // 从身份证提取的出生日期
      isLongTerm: false, // 是否长期有效
      rules: {
        real_name: { required: true, message: '请输入姓名' },
        idcard: { 
          required: true, 
          message: '请输入证件号码',
          validator: (value) => /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value),
          error: '请输入有效的18位身份证号码'
        },
        start_date: { required: true, message: '请选择有效期开始日期' },
        end_date: { 
          required: true, 
          message: '请选择有效期结束日期',
          validator: (value) => {
            if (!value) return false;
            if (this.isLongTerm) return true;
            
            // 检查开始日期是否小于失效日期
            if (this.form.startDate) {
              const start = new Date(this.form.startDate);
              const expire = new Date(value);
              return expire > start;
            }
            return true;
          },
          error: '有效期结束日期必须晚于开始日期'
        },
        idcard_image: { required: true, message: '请上传身份证正面' },
        idcard_image_b: { required: true, message: '请上传身份证反面' }
      },
	  url:'',
	  list: [ '大递卡', '骑士卡'],
	  current:0
    }
  },
  computed: {
    // 表单是否有效
    isFormValid() {
      for (let key in this.rules) {
        if (this.rules[key].required && !this.form[key]) {
          return false;
        }
        if (this.rules[key].validator && !this.rules[key].validator(this.form[key])) {
          return false;
        }
      }
      return true;
    }
  },
  onLoad() {
	  
  },
  methods: {
	sectionChange(index){
		this.current = index
	},
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },
    
    // 身份证号码输入事件
    onIdNumberInput(e) {
      const idNumber = e.target.value;
      this.form.idcard = idNumber;
      
      // 当输入满18位时，尝试提取出生日期
      if (idNumber.length === 18) {
        this.extractBirthDate(idNumber);
      } else {
        this.birthDate = '';
      }
	   if(!this.validateIdCard(this.form.idcard)){
	  		  uni.showToast({
	  		  	icon:'none',
	  			title:'身份证号码格式不正确'
	  		  })
	  		  return
	  	  }
      
      this.validateField('idcard');
    },
    
    // 从身份证号码提取出生日期
    extractBirthDate(idNumber) {
      try {
        const year = idNumber.substring(6, 10);
        const month = idNumber.substring(10, 12);
        const day = idNumber.substring(12, 14);
        this.birthDate = `${year}-${month}-${day}`;
      } catch (e) {
        this.birthDate = '';
      }
    },
    
    // 开始日期选择变化
    onStartDateChange(e) {
      this.form.start_date = e.detail.value;
      this.validateField('start_date');
      this.validateField('end_date'); // 重新验证失效日期
    },
    
    // 失效日期选择变化
    onExpireDateChange(e) {
      this.isLongTerm = false;
      this.form.end_date = e.detail.value;
      this.validateField('end_date');
    },
    
    // 长期有效选项变化
    onLongTermChange() {
      if (this.isLongTerm) {
        this.form.end_date = '';
      } else {
        // 如果之前是长期，现在取消，设置一个默认值
        if (!this.form.end_date) {
          const today = new Date();
          const nextYear = today.getFullYear() + 1;
          const month = String(today.getMonth() + 1).padStart(2, '0');
          const day = String(today.getDate()).padStart(2, '0');
          this.form.end_date = `${nextYear}-${month}-${day}`;
        }
      }
      this.validateField('end_date');
    },
    
    // 字段校验
    validateField(field) {
      const value = this.form[field];
      const rule = this.rules[field];
      
      if (rule.required && !value) {
        this.errors[field] = rule.message;
        return false;
      }
      
      if (rule.validator && !rule.validator(value)) {
        this.errors[field] = rule.error;
        return false;
      }
      
      this.errors[field] = '';
      return true;
    },
    
    // 选择图片
    chooseImage(type) {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
          // this.form[type] = res.tempFilePaths[0];
          // this.validateField(type);
		  const response = await this.$api.uploadFile('/Upload/File',res.tempFilePaths[0])
		  if(response.code == 200) {
			this.form[type] = response.url
		  }
        }
      });
    },
    validateIdCard(idCard) {
      // 清除空格并转换为大写
      idCard = idCard.trim().toUpperCase();
      
      // 基础格式校验
      const reg15 = /^[1-9]\d{5}\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}$/;
      const reg18 = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9X]$/;
      
      if (reg15.test(idCard)) {
        // 15位身份证校验
        return true; // 简化处理，实际项目中可能需要进一步校验
      } else if (reg18.test(idCard)) {
        // 18位身份证校验
        // 前17位权重因子
        const factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        // 校验码对应值
        const parity = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
        
        let sum = 0;
        for (let i = 0; i < 17; i++) {
          sum += parseInt(idCard.charAt(i)) * factor[i];
        }
        
        const checkCode = parity[sum % 11];
        return idCard.charAt(17) === checkCode;
      }
      
      return false;
    },
    // 提交表单
    async submitForm() {
      // 完整校验
      for (let key in this.rules) {
	  if (this.rules[key].required && !this.form[key]) {
			uni.showToast({
			  title: this.rules[key].message,
			  icon: 'none',
			  duration: 1000
			});
			return;
		  }
		}
      if(!this.validateIdCard(this.form.idcard)){
		  uni.showToast({
		  	icon:'none',
			title:'身份证号码格式不正确'
		  })
		  return
	  }
      // 模拟提交
	  this.form.type = this.current
      const res = await this.$api.post('/Business/add',this.form,true)
	  if(res.data.code === 200) {
		  setTimeout(() => {
		    uni.showToast({
		      title: '添加成功',
		      icon: 'success'
		    });
		    this.goBack();
		  }, 1000);
	  }
      // 实际项目中应调用API上传图片和表单数据
      
    }
  }
}
</script>

<style scoped lang="scss">
/* 页面基础样式 */
.whitelist-page {
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 24rpx;
  background: linear-gradient(90deg, #2c82c9, #3a9ee6);
  color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}
.back-btn {
  font-size: 32rpx;
}
.title {
  font-size: 36rpx;
  font-weight: bold;
}

/* 表单容器 */
.form-container {
  padding: 32rpx 24rpx;
}

/* 表单卡片 */
.form-card {
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.08);
  padding: 32rpx 24rpx;
}

/* 表单项 */
.form-item {
  margin-bottom: 32rpx;
}
.item-label {
  display: block;
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 16rpx;
}
.item-label::before {
  content: '*';
  color: #ff4d4f;
  margin-right: 8rpx;
}
.item-input {
  position: relative;
}
.item-input input, .item-input textarea {
  width: 92%;
  height: 80rpx;
  line-height: 80rpx;
  border: 1px solid #e5e5e5;
  border-radius: 10rpx;
  padding: 0 24rpx;
  font-size: 28rpx;
  color: #333;
}
.item-input textarea {
  height: 160rpx;
  line-height: 48rpx;
  padding: 16rpx 24rpx;
  resize: none;
}
.readonly-value {
  display: block;
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  border: 1px solid #e5e5e5;
  border-radius: 10rpx;
  padding: 0 24rpx;
  font-size: 28rpx;
  color: #999;
  background-color: #f9f9f9;
}
.counter {
  position: absolute;
  right: 24rpx;
  bottom: 16rpx;
  font-size: 22rpx;
  color: #999;
}
.tips {
  font-size: 22rpx;
  color: #999;
  margin-top: 12rpx;
}
.error-message {
  font-size: 22rpx;
  color: #ff4d4f;
  margin-top: 8rpx;
}

/* 日期选择器样式 */
.picker {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  border: 1px solid #e5e5e5;
  border-radius: 10rpx;
  padding: 0 24rpx;
  font-size: 28rpx;
  color: #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.arrow-icon {
  width: 28rpx;
  height: 28rpx;
}

/* 上传区域 */
.upload-container {
  position: relative;
}
.upload-box {
  width: 640rpx;
  height: 360rpx;
  position: relative;
  border: 1rpx dashed #e5e5e5;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  background-size: cover;
  background-position: center;
}
.upload-placeholder {
  text-align: center;
}
.upload-icon {
  font-size: 48rpx;
  color: #999;
  display: block;
}
.upload-text {
  font-size: 24rpx;
  color: #999;
}
.preview-img {
  width: 100%;
  height: 100%;
}
.upload-tips {
  font-size: 22rpx;
  color: #999;
  margin-top: 12rpx;
}

/* 提交按钮 */
.btn-container {
  padding: 32rpx 0;
}
.submit-btn {
  width: 100%;
  height: 96rpx;
  line-height: 96rpx;
  background: linear-gradient(90deg, #2c82c9, #3a9ee6);
  color: #fff;
  font-size: 32rpx;
  font-weight: 500;
  border-radius: 48rpx;
  box-shadow: 0 6rpx 16rpx rgba(44, 130, 201, 0.3);
}
.submit-btn:disabled {
  background: #e5e5e5;
  color: #999;
  box-shadow: none;
}
</style>